<?php
/**
 * Curl工具类
 * Author: 孙武 QQ:1228746736
 * Date: 2017/12/1
 * Time: 22:32
 */
namespace Curl;
class Curl
{
    /**curl发送post数据
     * @param $url string 目标url
     * @param $data array 需要传递的数组，将会被转换为json
     * @return mixed
     * @throws Exception
     */
    public static function curlPostJson($url, $data)
    {
        if (!is_array($data)) throw new \Exception('$data必须为数组数据');
        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_SAFE_UPLOAD, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        $curlRes = curl_exec($curl);
        curl_close($curl);
        return $curlRes;
    }


    /**
     * curlpost获取json数据
     * @param $url
     * @param $data
     * @return mixed
     */
    public static function curlGetJsonDataByPost($url, $data)
    {
        $data=self::curlPostJson($url,$data);
        return json_decode($data,true);
    }

    /**
     * curl发送get消息
     * @param $url
     * @return mixed f返回的消息
     * @throws \Exception
     */
    public static function curlGet($url)
    {
        if(is_array($url)) throw new \Exception('$url必须为字符串');
        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, false);
        $curlRes = curl_exec($curl);
        curl_close($curl);
        return $curlRes;
    }


    /**
     * curl获取json数据
     * @param $url
     * @return mixed
     */
    public static function curlGetJsonDataByGet($url)
    {
        return json_decode(self::curlGet($url),true);
    }


}